package pers.chao.cacheable.core;

import pers.chao.cacheable.core.annotation.CacheBitmap;
import pers.chao.cacheable.infrastructure.ErrorDesc;
import pers.chao.cacheable.infrastructure.utils.RedisOp;

/**
 * Description: bitmap缓存操作
 *
 * @author W.Chao
 * @date 2020/10/2 0:51
 **/
public class CacheBitmapProcessor extends AbstractCacheProcessor {
	private CacheBitmap annotation;

	private Integer pos;

	public CacheBitmapProcessor(CacheBitmap annotation) {
		this.annotation = annotation;
	}

	@Override
	protected void preInfo() {
		logger.info("[Cache bitmap pre INFO], @cache -> {}, @cacheBitmap -> {}", cacheConditionInfo(), annotation);
	}

	@Override
	public void parseRedisStructKeyOrOther() {
		// 清除模式不需要验证和解析pos
		if (evict) {
			return;
		}
		String posParam = annotation.pos();
		pos = Integer.valueOf(objectKeyParse(posParam, String.valueOf(pos)));
		if (pos < 1) {
			throw new CacheableException(ErrorDesc.BITMAP_POS_ERROR, pos);
		}
	}

	@Override
	public Object preQuery() {
		if (RedisOp.hasKey(finalKey)){
			return RedisOp.getBit(finalKey, pos);
		}
		return null;
	}

	@Override
	public void afterMethodOperate(Object o) {
		if (evict) {
			// 清除
			RedisOp.bitDel(key);
			return;
		}

		boolean isFirst = !RedisOp.hasKey(finalKey);

		// 缓存期限
		if (isFirst && isNeedExpire) {
			RedisOp.setBit(finalKey, pos, (Boolean) o, expire, unit);
		} else {
			RedisOp.setBit(finalKey, pos, (Boolean) o);
		}
	}

}
